const express = require("express");
const app = express();

// 连接MongoDB
const mongoose = require("mongoose");
const db = require("./config/keys").mongoURI;
mongoose
  .connect(db)
  .then(console.log("Connected to MongoDB"))
  .catch((err) => console.log(err));

const port = process.env.PORT || 5000;
app.get("/", (req, res) => {
  res.send("Hello World!");
});

// 使用body-parser库的两个方法来解析请求体
// urlencoded方法用于处理url编码数据
// json方法用于处理json数据
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// Passport验证token有效性，引入-初始化-配置
const passport = require("passport");
app.use(passport.initialize());
require("./config/passport")(passport);

// 引入路由模块
const users = require("./routes/api/users");
app.use("/api/users", users);
const profiles = require("./routes/api/profiles");
app.use("/api/profiles", profiles);

// 监听端口5000或生产环境变量指定的端口
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
